/**
 * 
 */
package ase.assignment.sts.api;

import java.sql.ResultSet;
import java.sql.SQLException;

import ase.assignment.sts.beans.CustomEntity;
import ase.assignment.sts.db.DBHandler;

/**
 * @author Lionel
 * 
 */
public class CustomHandler {
	private static CustomHandler instance = new CustomHandler();

	private CustomHandler() {

	}

	public static CustomHandler getInstance() {
		return instance;
	}

	public void create(CustomEntity custom) {
		String sql = "insert into customs values('" + custom.getName() + "','"
				+ custom.getPassword() + "','" + custom.getEmail() + "')";
		try {
			System.out.println(sql);
			DBHandler.getInstance().createStatement().executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBHandler.getInstance().dispose();
		}
	}

	public boolean login(String username, String password) {
		if (username == null || password == null) {
			return false;
		}
		boolean isOk = false;
		String sql = "select password from customs where name = '" + username
				+ "'";
		try {
			System.out.println(sql);
			ResultSet rs = DBHandler.getInstance().createStatement()
					.executeQuery(sql);			
			if (rs != null && rs.next()) {
				String pass = rs.getString(1).trim();
				isOk = pass != null && pass.equals(password);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBHandler.getInstance().dispose();
		}
		return isOk;
	}

	public void logout(String username) {

	}

	public void update(CustomEntity custom) {
		String sql = "update customs set password='" + custom.getPassword()
				+ "', email='" + custom.getEmail() + "' where name = '"
				+ custom.getName() + "'";
		try {
			DBHandler.getInstance().createStatement().executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBHandler.getInstance().dispose();
		}
	}

	public void close(String username) {
		String sql = "delete from customs where name = '" + username + "'";
		try {
			DBHandler.getInstance().createStatement().executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBHandler.getInstance().dispose();
		}
	}

}
